<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Component\Discount\Repositories\DiscountRepository;
use iBrand\EC\Open\Core\Services\DiscountService;
use iBrand\EC\Open\Server\Transformers\CouponTransformer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CouponController extends Controller
{
    private $couponRepository;
    private $discountService;
    private $discountRepository;

    public function __construct(
        CouponRepository $couponRepository, DiscountService $discountService, DiscountRepository $discountRepository
    )
    {
        $this->couponRepository = $couponRepository;
        $this->discountService = $discountService;
        $this->discountRepository = $discountRepository;
    }

    /**
     * @return \Dingo\Api\Http\Response
     * 优惠券列表
     */
    public function index()
    {
        $arr = [];
        //1.有效的 2.已使用的 3.已过期
        $type = request('type') ?: 1;

        $user = request()->user();
        if (1 == $type) {
            $coupons = $this->couponRepository->findActiveByUser($user->id);
        } elseif (2 == $type) {
            $coupons = $this->couponRepository->findUsedByUser($user->id);
        } else {
            $coupons = $this->couponRepository->findInvalidByUser($user->id);
        }
        if($coupons){
            foreach ($coupons as $key=>&$v){
                //dd($v['discount']['actions'][0]['configuration']);
                $discount_money = json_decode($v['discount']['actions'][0]['configuration'],true);
                $rules_money = (json_decode($v['discount']['rules'][0]['configuration'],true));
                $type = $v['discount']['rules'][0]['type'];
                if($type=='item_total'){
                    $v['discount']['discount_type'] = '满减券';
                }
                $v['discount']['rules_money'] = $rules_money['amount']/100;
                $v['discount']['discount_money'] = $discount_money['amount']/100;
                unset($v['discount']['actions']);
                unset($v['discount']['rules']);
                unset($v['discount']['coupon_based']);
                unset($v['discount']['tags']);
                unset($v['discount']['intro']);
                unset($v['discount']['code']);
                unset($v['discount']['exclusive']);
                $arr[$key] = $v['discount'];
            }
        }
        return $this->success($arr);
    }


    /**
     * @return \Dingo\Api\Http\Response|mixed
     * 检查订单是否可以用优惠券
     */
    public function check(){
        $arr = [];
        $money = request('money');
        $goods_id = request('goods_id');

        if(!$money){
            return $this->failed('缺少参数！');
        }
        $user = request()->user();
        $coupons = $this->couponRepository->findActiveByUser($user->id);
        if($coupons){
            foreach ($coupons as $key=>&$v){
                $is_goods = 0;
                $discount_money = json_decode($v['discount']['actions'][0]['configuration'],true);
                $rules_money = (json_decode($v['discount']['rules'][0]['configuration'],true));
                $type = $v['discount']['rules'][0]['type'];
                if($type=='item_total'){
                    $v['discount']['discount_type'] = '满减券';
                }
                $v['discount']['rules_money'] = $rules_money['amount']/100;
                $v['discount']['discount_money'] = $discount_money['amount']/100;
                if($goods_id){
                    foreach ($v['discount']['rules'] as $value){
                        if($value['type']=='contains_product'){
                            $configuration = json_decode($value['configuration'],true);
                            $spus = explode(',',$configuration['spu']);
                            if(in_array($goods_id,$spus)){
                                $is_goods = 1;
                            }
                        }

                    }
                }
                //判断金额
                if($money < $v['discount']['rules_money']){
                    continue;
                }
                if(time() < strtotime($v['discount']['usestart_at']) || time() > strtotime($v['discount']['useend_at'])){
                    continue;
                }
                unset($v['discount']['actions']);
                unset($v['discount']['rules']);
                unset($v['discount']['coupon_based']);
                unset($v['discount']['tags']);
                unset($v['discount']['intro']);
                unset($v['discount']['code']);
                unset($v['discount']['exclusive']);
                //查询优惠券code
                $coupon = DB::table('ibrand_discount_coupon')->where(['user_id'=>$user->id,'discount_id'=>$v['discount']['id']])->where('used_at','=',NULL)->first();
                if(!$coupon){
                    return $this->failed('网络繁忙，请重试！');
                }
                $v['discount']['coupon_code'] = $coupon->code;
                //判断是否是单品
                if($goods_id){
                    if($is_goods==1){
                        $arr[$key] = $v['discount'];
                        break;
                    }
                }else{
                    $arr[$key] = $v['discount'];
                }
            }
            $arrs = array_values($arr);

            return $this->success($arrs);
        }
    }


    /**
     * @return \Dingo\Api\Http\Response|mixed
     * 根据商品ID查询对应的优惠券
     */
    public function getGoodsCoupon(){
        $user = request()->user();
        $arr = [];
        $goods_id = request('goods_id');
        if(!$goods_id){
            return $this->failed('缺少信息！');
        }
        //查询带有该商品的优惠券
        //$ress = DB::table('ibrand_discount_rule')->where(['type'=>'contains_product'])->get();
        $ress = DB::table('ibrand_discount_rule')->leftjoin('ibrand_discount_action','ibrand_discount_action.discount_id','=','ibrand_discount_rule.discount_id')->where(['ibrand_discount_rule.type'=>'contains_product'])->get(['ibrand_discount_rule.configuration as rconfiguration','ibrand_discount_action.configuration as aconfiguration','ibrand_discount_rule.discount_id']);
        if($ress){
            foreach ($ress as $v){
                $rconfiguration = json_decode($v->rconfiguration,true);
                //$aconfiguration = json_decode($v->aconfiguration,true);
                $spus = explode(',',$rconfiguration['spu']);
                if(in_array($goods_id,$spus)){
                    //$coupon = DB::table('ibrand_discount_rule')->leftjoin('ibrand_discount_action','ibrand_discount_action.discount_id','=','ibrand_discount_rule.discount_id')->where(['ibrand_discount_action.discount_id'=>$v->discount_id])->first();
                    $coupon = $this->discountRepository->find($v->discount_id);
                    $coupon['discount_type'] = '满减券';
                    $ress_money = DB::table('ibrand_discount_rule')->leftjoin('ibrand_discount_action','ibrand_discount_action.discount_id','=','ibrand_discount_rule.discount_id')->where(['ibrand_discount_rule.type'=>'item_total'])->first(['ibrand_discount_rule.configuration as rconfiguration','ibrand_discount_action.configuration as aconfiguration']);
                    $rconfiguration_money = json_decode($ress_money->rconfiguration,true);
                    $aconfiguration_money = json_decode($ress_money->aconfiguration,true);
                    $coupon['rules_money'] = $rconfiguration_money['amount']/100;
                    $coupon['discount_money'] = $aconfiguration_money['amount']/100;
                    unset($coupon['actions']);
                    unset($coupon['rules']);
                    unset($coupon['coupon_based']);
                    unset($coupon['tags']);
                    unset($coupon['intro']);
                    unset($coupon['code']);
                    unset($coupon['exclusive']);
                    Redis::set('coupon_'.$v->discount_id,json_encode($coupon));
                    if(time() <= strtotime($coupon->ends_at)){
                        $arr[] = $coupon;
                    }
                }
            }
            return $this->success($arr);
        }
        return $this->failed([]);
    }

    /**
     * 获取优惠券
     */
    public function receiveCounpon()
    {
        try{
            $user = request()->user();
            $discount_id = request('discount_id');
            if (!$discount_id) return $this->failed('缺少信息！');
            //查询优惠券信息
            $discount = DB::table('ibrand_discount')->where(['id' => $discount_id,'status'=>1])->orderBy('id', 'desc')->first();
            if (!$discount) return $this->failed('优惠券信息错误！');
            //判断是否已经领取过该优惠券了
            $ress = DB::table('ibrand_discount_coupon')->where(['user_id' => $user->id, 'discount_id' => $discount->id])->first();
            if ($ress) return $this->failed('您已经领取过该优惠券了');
            //判断领取时间段
            //if(time())
            if(time() < strtotime($discount->starts_at) || time() > strtotime($discount->ends_at)){
                return $this->failed('未在领取时间内，现在还不能领取哦！');
            }
            $code = uniqid();
            DB::beginTransaction();
            //领取优惠券
            $res = DB::table('ibrand_discount_coupon')->insert(['user_id'=>$user->id,'discount_id'=>$discount->id,'code'=>$code,'expires_at'=>$discount->useend_at,'created_at'=>date('Y-m-d H:i:s',time())]);
            if(!$res){
                return $this->failed('领取失败，请重试！');
            }
            //更新数量
            DB::table('ibrand_discount')->where(['id'=>$discount->id])->increment('used');
            DB::commit();
            return $this->success('领取成功！');
        }catch (\Exception $exception){
            DB::rollBack();
            savelog('getCounpon', '卡券ID'.$discount_id.'错误：'.$exception->getMessage().$exception->getLine());
            //var_dump($exception->getMessage() . $exception->getTraceAsString());
            return $this->failed('领取失败');
        }

    }

    /**
     * 获取优惠券信息
     */
    public function getCoupon(){
        $user = request()->user();
        $arr =[];
        $discount_id = request('discount_id');
        if (!$discount_id) return $this->failed('缺少信息！');
        $res = Redis::get('coupon_'.$discount_id);
        if($res){
            $arr = json_decode($res,true);
        }else{

        }
    }


    /**
     * 领取优惠券
     */
    public function receive(){
        try{
            $user = request()->user();
            $discount_id = 9;
            if (!$discount_id) return $this->failed('缺少信息！');
            //查询优惠券信息
            $discount = DB::table('ibrand_discount')->where(['id' => $discount_id,'status'=>1])->orderBy('id', 'desc')->first();
            if (!$discount) return $this->failed('优惠券信息错误！');
            //判断是否已经领取过该优惠券了
            $ress = DB::table('ibrand_discount_coupon')->where(['user_id' => $user->id, 'discount_id' => $discount->id])->first();
            if ($ress) return $this->failed('您已经领取过该优惠券了');
            //判断领取时间段
            //if(time())
            if(time() < strtotime($discount->starts_at) || time() > strtotime($discount->ends_at)){
                return $this->failed('未在领取时间内，现在还不能领取哦！');
            }
            $code = uniqid();
            DB::beginTransaction();
            //领取优惠券
            $res = DB::table('ibrand_discount_coupon')->insert(['user_id'=>$user->id,'discount_id'=>$discount->id,'code'=>$code,'expires_at'=>$discount->useend_at,'created_at'=>date('Y-m-d H:i:s',time())]);
            if(!$res){
                return $this->failed('领取失败，请重试！');
            }
            //更新数量
            DB::table('ibrand_discount')->where(['id'=>$discount->id])->increment('used');
            DB::commit();
            return $this->success('领取成功！');
        }catch (\Exception $exception){
            DB::rollBack();
            savelog('getCounpon', '卡券ID'.$discount_id.'错误：'.$exception->getMessage().$exception->getLine());
            //var_dump($exception->getMessage() . $exception->getTraceAsString());
            return $this->failed('领取失败');
        }
    }



    public function show($couponId)
    {
        $coupon = $this->couponRepository->with('discount', 'discount.rules', 'discount.actions')->find($couponId);

        $user = request()->user();

        if ($user->cant('update', $coupon)) {
            return $this->failed('无权操作');
        }

        return $this->success($coupon);
    }

    public function create()
    {
        $discount = $this->discountRepository->create(request()->except('rule_type', 'rule_value', 'action_type', 'action_value'));

        $ruleType = request('rule_type');

        if ($ruleType == 'cart_quantity') {
            $ruleData = ['count' => request('rule_value')];
        } else {
            $ruleData = ['amount' => request('rule_value')];
        }

        $actionType = request('action_type');

        if ($actionType == 'order_fixed_discount') {
            $actionData = ['amount' => request('action_value')];
        } else {
            $actionData = ['percentage' => request('action_value')];
        }

        $discount->rules()->create(['type' => $ruleType, 'configuration' => json_encode($ruleData)]);
        $discount->actions()->create(['type' => $actionType, 'configuration' => json_encode($actionData)]);

        return $this->success();
    }

    public function take()
    {
        $discount = $this->discountRepository->find(request('discount_id'));

        if(!$discount->coupon_based){
            return $this->failed('非优惠券，无法领取');
        }

        $coupon = $this->couponRepository->create(['discount_id'=>request('discount_id'),'user_id'=>request()->user()->id,
            'code'=>uniqid()]);

        return $this->success($coupon);
    }
}
